package com.wh.book2.controller;

import com.wh.book2.model.BookInfo;
import com.wh.book2.model.PageRequest;
import com.wh.book2.model.PageResult;
import com.wh.book2.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {
    @Autowired
    BookService bookService;

    @RequestMapping(value = "/add", produces = "application/json")
    public String addBook(BookInfo bookInfo) {
        log.info("添加图书，接收参数bookInfo:{}", bookInfo);
        if (!StringUtils.hasLength(bookInfo.getBookName()) ||
                !StringUtils.hasLength(bookInfo.getAuthor()) ||
                bookInfo.getCount() == null ||
                bookInfo.getPrice() == null ||
                !StringUtils.hasLength(bookInfo.getPublish()) ||
                bookInfo.getStatus() == null) {
            return "输入参数不合法";
        }
        try {
            int result = bookService.insertBook(bookInfo);
            if (result > 0) {
                return "";
            }
        } catch (Exception e) {
            log.error("添加图书异常, e: ", e);
        }
        return "添加失败";
    }

    @RequestMapping("/getBookListByPage")
    public PageResult<BookInfo> getBookListByPage(PageRequest pageRequest) {
        log.info("查询图书列表, 请求参数pageRequest: {}", pageRequest);
        return bookService.getBookListByPage(pageRequest);
    }

    @RequestMapping("/getBookById")
    public BookInfo getBookById(Integer id) {
        log.info("查询图书列表, 请求参数id: {}", id);
        return bookService.getBookById(id);
    }

    @RequestMapping(value = "/updateBook", produces = "application/json")
    public String updateBook(BookInfo bookInfo) {
        log.info("更新图书, bookInfo: {}", bookInfo);
        Integer result = bookService.updateBookById(bookInfo);
        if (result > 0) {
            return "";
        }
        return "内部错误, 请联系管理员";
    }

    @RequestMapping("/deleteBook")
    public boolean deleteBook(Integer id) {
        log.info("删除图书, bookId: {}", id);
        Integer result = bookService.deleteBookById(id);
        if (result > 0) {
            return true;
        }
        return false;
    }

    @RequestMapping(value = "/batchDelete", produces = "application/json")
    public String batchDelete(@RequestParam(required = false) List<Integer> ids) {
        log.info("批量删除图书, ids: {}", ids);
        Integer result = bookService.batchDelete(ids);
        if (result > 0) {
            return "";
        }
        return "删除失败, 请联系管理员";
    }
}
